import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { Button, Card, DatePicker, Icon, message, Radio, Select, Table } from 'antd';
import { PageLoading } from '@ant-design/pro-layout';
import EchartsBar from '@/components/Dashboard/EchartsBar';
import EchartsPie from '@/components/Dashboard/EchartsPie';
// import { ENERGYCATEGORY_PRICE } from '@/utils/constants';
import memoryUtils from '@/utils/memoryUtils';

const { RangePicker } = DatePicker;
const { Option } = Select;

class index extends Component {

  static defaultProps = {
    searchParamsValue: [],
    energyCategoryType: ''
  }

  constructor(props) {
    super(props);
    this.DATE_FORMAT = ['YYYY-MM-DD', 'YYYY-MM', 'YYYY'];
    this.DATE_MODE = [['date', 'date'], ['month', 'month'], ['year', 'year']];
    this.state = {
      showType: 'bar',
      // computeType: Object.keys(memoryUtils.ENERGYCATEGORY_PRICE)[0],
      computeType: props.computeTypes ? props.computeTypes[0].value : '',
      searchParamsValueStr: props.searchParamsValue?props.searchParamsValue.join('|||'):'',
      dateValue:[],
      period: 0,
      dateRangeShow: false,
    };
  }

  searchData = () => {
    const { searchParamsValueStr, dateValue, period, computeType } = this.state;
    if (!searchParamsValueStr || searchParamsValueStr.trim() === '') {
      message.warning('查询参数不能为空');
      return false;
    } else if (!dateValue || dateValue.length < 2) {
      message.warning('请选择查询日期');
      return false;
    } else {
      const payload = { h:searchParamsValueStr, t:1, p:period, startTime: dateValue[0].format(this.DATE_FORMAT[period]), endTime: dateValue[1].format(this.DATE_FORMAT[period]) };
      const energyPrice = memoryUtils.ENERGYCATEGORY_PRICE[computeType]?memoryUtils.ENERGYCATEGORY_PRICE[computeType]:'[]';
      payload.price = energyPrice;
      this.props.dispatch({ type: 'energyStatistics/fetchSum', payload });
    }
  };

  createEchartsData = (lists = []) => {
    const data = [];
    lists.forEach(list => {
      list.forEach(item => {
        data.push({ id: item.id, name: item.name, value: parseFloat(item.value)});
      })
    });
    data.sort((a, b)=>b.value-a.value);
    const names = data.map(item=>item.name);
    return { data, names};
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.searchParamsValue !== this.props.searchParamsValue) {
      this.setState({ searchParamsValueStr: nextProps.searchParamsValue?nextProps.searchParamsValue.join('|||'):'' });
    }
    // if(nextProps.energyCategoryType !== this.props.energyCategoryType) {
    //   this.setState({ energyPrice: memoryUtils.ENERGYCATEGORY_PRICE[nextProps.$handle]?memoryUtils.ENERGYCATEGORY_PRICE[nextProps.$handle]:'[]' });
    // }
  }

  componentWillUnmount() {
    this.props.dispatch({ type: 'energyStatistics/clearAll' });
  }

  handleComputeTypeChange = (e)=> {
    this.setState({
      computeType: e.target.value
    }, () => {
      if (this.props.lists && this.props.lists.length > 0) {
        this.searchData();
      }
    });
  }

  render() {
    const { computeTypes, lists, loading } = this.props;
    if(loading) {
      return <PageLoading/>;
    }
    const { showType, computeType, dateValue, period, dateRangeShow } = this.state;
    const title = (
      <span className={'space8'}>
        <Radio.Group name={'computeType'} value={computeType} onChange={this.handleComputeTypeChange}>
          {computeTypes.map(item=>(<Radio value={item.value}>{item.label}</Radio>))}
        </Radio.Group>
        <RangePicker
          allowClear={false}
          showTime={false}
          open={dateRangeShow}
          mode={this.DATE_MODE[period]}
          format={this.DATE_FORMAT[period]}
          value={dateValue}
          placeholder={['开始时间', '结束时间']}
          onChange={value=> this.setState({ dateValue: value})}
          onPanelChange={value=> this.setState({ dateValue: value, dateRangeShow: false})}
          onOpenChange={value=> this.setState({ dateRangeShow: value})}
        />
        <Select value={period} onChange={value=> this.setState({ period: value})}>
          <Option value={0}>日</Option>
          <Option value={1}>月</Option>
          <Option value={2}>年</Option>
        </Select>
      </span>
    );
    const extra = (
      <span className={'space8'}>
        <Radio.Group name={'showType'} value={showType}
                     buttonStyle='solid'
                     onChange={event => this.setState({ showType: event.target.value })}>
          <Radio.Button value='bar'><Icon type='bar-chart'/></Radio.Button>
          <Radio.Button value='table'><Icon type='table'/></Radio.Button>
          <Radio.Button value='pie'><Icon type='pie-chart'/></Radio.Button>
        </Radio.Group>
        <Button type='primary' onClick={() => this.searchData()}>
          <Icon type={'search'}/>查询
        </Button>
      </span>
    );
    let dom = <></>;
    const { data, names} = this.createEchartsData(lists);
    if (showType === 'table') {
      const columns = [{
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
      }, {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
      }, {
        title: '统计值',
        dataIndex: 'value',
        key: 'value',
      }];
      dom = (<Table
        title={() => '查询结果'}
        className={'common-table-wrapper'}
        columns={columns}
        dataSource={data}
        rowKey='_id'
        loading={loading}
        pagination={{
          total: data.length,
          pageSize: data.length,
          current: 1
        }}
      />);
    } else if(showType === 'bar') {
      dom = (<EchartsBar ref={(e)=> { this.echartsBar = e; }} title='查询结果' legends={names} data={data} bSubscribe={false} bDashboard={false}/>);
    } else {
      dom = (<EchartsPie ref={(e)=> { this.echartsBar = e; }} title='查询结果' legends={names} data={data} bSubscribe={false} bDashboard={false}/>);
    }
    return (
      <Card title={title} extra={extra} style={{ height: '100%' }} bodyStyle={{ height: '80%' }}>{dom}</Card>
    );
  }
}

index.propTypes = {
  searchParamsValue: PropTypes.array,
  energyCategoryType: PropTypes.string,
  computeTypes: PropTypes.array.isRequired
};

export default connect(({ energyStatistics, loading }) => ({
  ...energyStatistics,
  loading: loading.effects['energyStatistics/fetchSum'],
}))(index);

